﻿Imports CrystalDecisions.Shared
Imports TNCDAL
Imports HTLibrary

Public Class ucDebit
    Dim index As Integer = 0
    Dim uti As New Utilities
    Dim mFile As New MFiles
    Dim mdb As New MDebit
    Dim _idHbl As Integer = 0
    Dim _idfile As Integer
    Private currencyVND As tblCurrency = Nothing
    Private currencyForeign As tblCurrency = Nothing
    Dim isLoadData As Boolean = False
    Public Sub New()

        ' This call is required by the designer.
        InitializeComponent()
        DataGridViewHelper.DataGridView_InitEvent(grid)
        ' Add any initialization after the InitializeComponent() call.

    End Sub
    Public Sub New(ByVal idFile As Integer)
        InitializeComponent()
        DataGridViewHelper.DataGridView_InitEvent(grid)
        txtIDFile.Text = idFile
        _idfile = idFile
    End Sub
    Public Sub New(ByVal idFile As Integer, ByVal idHbl As Integer)
        InitializeComponent()
        DataGridViewHelper.DataGridView_InitEvent(grid)
        txtIDFile.Text = idFile
        _idfile = idFile
        _idHbl = idHbl
    End Sub
    'Load dữ liệu vào combobox
    'hiển thị tiền và tỉ giá 
    Private Sub LoadData()
        ' util.FillCurrencyExchangeCombo(cbCurrencyExchange)
        'util.FillSellingFeeCombo(cbFee)
        'util.FillCurrencyCombo(cbCurrency)
        'uti.FillUnitCombo(cbUnit)

        dateDebit.Value = DateTime.Now()
    End Sub
    Private Sub ucDebit_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
        LoadCurrency()
        LoadData()
        'Lấy thông tin khách hàng từ idFile truyền qua
        Dim mfile As New MFiles
        Dim mfe As New MFileExchange
        Dim mcus As New MCustomer
        Dim idCus As Integer
        idCus = mfile.getCustomerOfFile(txtIDFile.Text)
        txtCustomerName.Text = mcus.getCustomerNameOfFile(idCus)
        txtFileNumber.Text = mfile.getFileNoFile(txtIDFile.Text)
        txtTel.Text = mcus.getTelCustomerOfFile(idCus)
        'txtTigia.Text = mfile.GetRatioCurrencyFollowHBL(txtIDFile.Text, _idHbl)
        'txtTigia.Text = mfe.GetRatioCurrencyFollowHBL(_idfile, _idHbl)
        txtETD.Text = mfile.getETDOfFile(_idHbl)
        txtPOD.Text = mfile.getPODOfFile(_idHbl)
        txtBL.Text = mfile.getBLNameOfFile(_idHbl)
        'THÊM TẤT CẢ PHÍ SELLING CHO FILE ----------
        'Dim sellingList = mfile.getSellingFeeOfFile(_idfile)
        'For Each obj As tblSellingFee In sellingList
        '    Dim _ucDebitDetail As New ucDebitDetail(_idfile, obj.ID_Fee)
        '    With _ucDebitDetail
        '        .Name = "ucDebit" & index.ToString
        '        .Left = 0
        '        .Top = index * .Height
        '    End With
        '    Me.panelFee.Controls.Add(_ucDebitDetail)
        '    index = index + 1
        'Next
        'Try
        '    'Lấy danh sách các bill of lading của file
        '    Dim bills = mfile.GetBillOfLadingOfFile(_idfile)
        '    txtBL.Text = bills
        'Catch ex As Exception
        '    MessageBox.Show(ex.Message)
        'End Try
        '-----------------------
        Dim sellingFee = mdb.GetSellingFeeOfFile(_idfile, _idHbl)

        grid.DataSource = sellingFee

    End Sub
    Private Sub LoadCurrency()
        Dim listCurrency As New List(Of tblCurrency)
        'Load thông tin tiền vào ô
        Dim ctrlCurrency As New MCurrencies
        currencyVND = ctrlCurrency.GetCurrencyByCode("VND")
        Dim currencyForeign = uti.GetCurrencyOfFile(_idfile)
        If (currencyVND IsNot Nothing) Then
            listCurrency.Add(currencyVND)
        End If
        If (currencyForeign IsNot Nothing) Then
            listCurrency.Add(currencyForeign)

        Else

        End If
        'cboCurrency.DataSource = listCurrency
        'cboCurrency.DisplayMember = "Code"
        'cboCurrency.ValueMember = "ID_Currency"
        'If (cboCurrency.Items.Count > 0) Then
        '    cboCurrency.SelectedIndex = 0
        'End If

    End Sub
    Public Sub InsertUnit()
        'Chèn Unit vào báo cáo

        For index = 0 To grid.Rows.Count - 1

            'Lấy thông tin Fee xem đó là loại phí gì
            Dim FeeName As String = grid.Rows(index).Cells("cbFee").Value.ToString()
            'Kiểm tra
            'Dim isBill As Boolean = uti.IsBillFee(FeeName)
            'Nếu là Phí Bill thì
            'grid.Rows(index).Cells("cbUnit").ReadOnly = False
            'If isBill Then

            '    grid(0, index).Value = 2

            'Else
            '    grid.Rows(index).Cells("cbUnit").Value = 1

            'End If
            grid.Rows(index).Cells("clnTax").Value = 0

            'If grid.Rows(index).Cells("cbCurrency").Value.ToString().Trim() = "VND" Then
            '    'Nếu là tiền việt thì
            '    grid.Rows(index).Cells("clnPrice").Value = grid.Rows(index).Cells("clnUnitPrice").Value * grid.Rows(index).Cells("clnQuantity").Value

            'Else
            '    grid.Rows(index).Cells("clnPrice").Value = grid.Rows(index).Cells("clnUnitPrice").Value * grid.Rows(index).Cells("clnQuantity").Value * Integer.Parse(txtTigia.Text.ToString().Replace(",", ""))

            'End If



        Next

    End Sub
    Public Sub InsertPriceFollowCurrency()
        'Chèn Unit vào báo cáo

        For index As Integer = 0 To grid.Rows.Count - 1

            'Lấy thông tin Currency xem đó là loại phí gì
            Dim Currency As String = grid.Rows(index).Cells("cbCurrency").Value.ToString()
            'Kiểm tra tiền đang chọn là tiền gì
            Dim currencyNow As String = "VND" 'cboCurrency.Text.Trim()
            'Nếu là tiền Việt giữ nguyên
            grid.Rows(index).Cells("cbCurrency").ReadOnly = False
            
            If grid.Rows(index).Cells("cbCurrency").Value.ToString().Trim() = "VND" Then
                'Nếu là tiền việt thì coi thử hiện tại muốn tính theo tiền gì

                If currencyNow = "VND" Then
                    grid.Rows(index).Cells("clnPrice").Value = grid.Rows(index).Cells("clnUnitPrice").Value * grid.Rows(index).Cells("clnQuantity").Value
                Else
                    'Đổi tiền
                    grid.Rows(index).Cells("clnPrice").Value = CDbl(grid.Rows(index).Cells("clnUnitPrice").Value * grid.Rows(index).Cells("clnQuantity").Value) / CDbl(grid.Rows(index).Cells("clnRatio").Value)
                End If


            Else
                'Nếu là tiền bình thường(k cần nhân tỉ giá)

                'If currencyNow = "VND" Then
                '    'cần phải nhân tỉ giá
                '    grid.Rows(index).Cells("clnPrice").Value = grid.Rows(index).Cells("clnUnitPrice").Value * grid.Rows(index).Cells("clnQuantity").Value * CDbl(txtTigia.Text.Replace(",", ""))
                'Else
                '    'Đổi tiền
                '    grid.Rows(index).Cells("clnPrice").Value = CDbl(grid.Rows(index).Cells("clnUnitPrice").Value * grid.Rows(index).Cells("clnQuantity").Value)
                'End If
                ''grid.Rows(index).Cells("clnPrice").Value = grid.Rows(index).Cells("clnUnitPrice").Value * grid.Rows(index).Cells("clnQuantity").Value * Integer.Parse(txtTigia.Text.ToString().Replace(",", ""))

            End If



        Next

    End Sub
    Private Sub btnPrintdebit_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnPrintdebit.Click
        'Khi chọn in sẽ lưu các số liệu vào dataset
        Dim dsReport1 As New dsReport
        Dim dtDebit As DataTable = dsReport1.Tables("dtDebit")
        Dim dtRow As DataRow

        'If txtTigia.Text = "" Then
        '    MessageBox.Show("Chưa có tỉ giá")
        '    Return
        'End If

        'For i As Integer = 0 To index - 1
        '    'Duyệt qua các ucControl
        '    'Lấy ra từng uc
        '    Dim ucDebitDetail As ucDebitDetail = CType(Me.panelFee.Controls(i), ucDebitDetail)

        '    dtRow = dtDebit.NewRow()
        '    dtRow("ID") = (i + 1).ToString() & "/"

        '    If ucDebitDetail.txtTax.Text <> "" Then
        '        dtRow("CHITIET") = ucDebitDetail.cbFee.Text & ": " & ucDebitDetail.txtUnitPrice.Text.Trim() & ucDebitDetail.cbCurrency.Text.Trim() _
        '   & " /" & ucDebitDetail.cbUnit.Text.Trim() & "+" & ucDebitDetail.txtTax.Text & "% TAX"
        '    Else
        '        dtRow("CHITIET") = ucDebitDetail.cbFee.Text.TrimEnd() & ": " & ucDebitDetail.txtUnitPrice.Text.TrimEnd() & ucDebitDetail.cbCurrency.Text _
        '   & " /" & ucDebitDetail.cbUnit.Text
        '    End If
        '    dtRow("DEBIT") = ucDebitDetail.txtPrice.Text
        '    dtRow("GHICHU") = ucDebitDetail.txtNote.Text


        '    dtDebit.Rows.Add(dtRow)
        'Next
        Dim stt = 1
        For i = 0 To grid.Rows.Count - 1

            If grid.Rows(i).Cells("clnUnitPrice").Value <> 0 Then
                dtRow = dtDebit.NewRow()
                dtRow("ID") = (stt).ToString() & "/"
                'Lấy giá trị tiền

                If CType(grid.Rows(i).Cells("clnTax").Value, Integer) <> 0 Then
                    '     dtRow("CHITIET") = grid.Rows(i).Cells("cbFee").Value() & ": " & grid.Rows(i).Cells("clnUnitPrice").Value & grid.Rows(i).Cells("cbCurrency").Value().ToString.Trim() _
                    '& " /" & util.GetNameUnit(grid.Rows(i).Cells("cbUnit").Value) & "+" & grid.Rows(i).Cells("clnTax").Value & "% TAX"
                    dtRow("CHITIET") = grid.Rows(i).Cells("cbFee").Value() & ": " & grid.Rows(i).Cells("clnTax").Value & "% TAX"

                Else
                    ' dtRow("CHITIET") = grid.Rows(i).Cells("cbFee").Value() & ": " & grid.Rows(i).Cells("clnUnitPrice").Value & grid.Rows(i).Cells("cbCurrency").Value().ToString().Trim() _
                    '& " /" & util.GetNameUnit(grid.Rows(i).Cells("cbUnit").Value)
                    dtRow("CHITIET") = grid.Rows(i).Cells("cbFee").Value() & ": "
                End If

                If grid.Rows(i).Cells("clnPrice").Value IsNot Nothing Then
                    dtRow("DEBIT") = grid.Rows(i).Cells("clnPrice").Value '* grid.Rows(i).Cells("clnRatio").Value
                Else
                    Return
                End If


                dtRow("GHICHU") = grid.Rows(i).Cells("clnDescription").Value


                dtDebit.Rows.Add(dtRow)
                stt += 1
            End If



            'Next
        Next
        'Lấy giá tiền để biết có chuyển phần tỉ giá qua hay không
        Dim currencyNow As String = "VND"  'cboCurrency.Text.Trim()
        Dim objRpt As New crptDebit
        objRpt.SetDataSource(dtDebit)

        If currencyNow = "VND" Then
            frmMain.AddNewDockContainerItem("ViewDebitNote", "Debit Note", New ucReportViewer(objRpt, "TO: " & txtCustomerName.Text.Trim(), "TEL: " & txtTel.Text, dateDebit.Value.ToString("dd/MM/yyyy"), _
                                "F" & txtFileNumber.Text.TrimEnd() & "/" & DateTime.Now().Year(), _
                               "", "ETD: " & txtETD.Text, _
                              "POD: " & txtPOD.Text, "40x", "B/L: " & txtBL.Text))

        Else
            frmMain.AddNewDockContainerItem("ViewDebitNote", "Debit Note", New ucReportViewer(objRpt, "TO: " & txtCustomerName.Text.Trim(), "TEL: " & txtTel.Text, dateDebit.Value.ToString("dd/MM/yyyy"), _
                                "F" & txtFileNumber.Text.TrimEnd() & "/" & DateTime.Now().Year(), _
                               "Ti gia: 0000" & " (" & currencyNow & ")", "ETD: " & txtETD.Text, _
                              "POD: " & txtPOD.Text, "40x", "B/L: " & txtBL.Text))

        End If

       
    End Sub

    Private Sub LabelX8_KeyPress(ByVal sender As System.Object, ByVal e As System.Windows.Forms.KeyPressEventArgs)
        If Not Char.IsControl(e.KeyChar) And Not Char.IsDigit(e.KeyChar) Then
            e.Handled = True
        End If
    End Sub

    Private Sub grid_CellEndEdit(ByVal sender As System.Object, ByVal e As System.Windows.Forms.DataGridViewCellEventArgs) Handles grid.CellEndEdit
        Select Case e.ColumnIndex
            Case 0
                'tự động cập nhật lại giá trị của price

                Dim clnunit As String = ""
                Dim clnquan As String = ""
                Dim clnpri As String = ""
                Dim clntax As String = ""
                Dim clncurr As String = ""
                Dim clnratio As String = ""
                'If isNew Then
                '    gridTinhTong = grid
                '    clnunit = "UnitPrice"
                '    clnquan = "Quantity"
                '    clnpri = "Price"
                'Else
                'gridTinhTong = gridEdit
                clnunit = "clnUnitPrice"
                clnquan = "clnQuantity"
                clnpri = "clnPrice"
                clntax = "clnTax"
                clncurr = "cbCurrency"
                clnratio = "clnratio"
                'End If
                Try
                    Dim UnitPrice As Double = Double.Parse(grid.Rows(e.RowIndex).Cells(clnunit).Value.ToString)
                    Dim Quantity As Double = Double.Parse(grid.Rows(e.RowIndex).Cells(clnquan).Value.ToString)
                    Dim Tax As Double = Double.Parse(grid.Rows(e.RowIndex).Cells(clntax).Value.ToString)
                    Dim Currency As String = grid.Rows(e.RowIndex).Cells(clncurr).Value.ToString
                    Dim Ratio As Double = grid.Rows(e.RowIndex).Cells(clnratio).Value.ToString

                    Dim total As Double = UnitPrice * Quantity
                    If Tax <> 0 Then



                        If Currency.Trim() = "VND" Then
                        Else
                            total = total * Ratio

                        End If
                        total = total + (total * Tax / 100)
                    Else
                        If Currency.Trim() = "VND" Then
                        Else
                            total = total * Ratio

                        End If
                    End If


                    grid.Rows(e.RowIndex).Cells(clnpri).Value = total
                Catch ex As Exception
                    grid.Rows(e.RowIndex).Cells(clnpri).Value = 0
                End Try
        End Select

    End Sub

    Private Sub grid_CellBeginEdit(ByVal sender As System.Object, ByVal e As System.Windows.Forms.DataGridViewCellCancelEventArgs) Handles grid.CellBeginEdit
        'If ((e.ColumnIndex = 2) Or (e.ColumnIndex = 2) Or (e.ColumnIndex = 2)) AndAlso e.RowIndex < grid.RowCount Then e.Cancel = True

    End Sub
    Dim FinishLoad As Boolean = False
    Private Sub grid_DataBindingComplete(ByVal sender As System.Object, ByVal e As System.Windows.Forms.DataGridViewBindingCompleteEventArgs) Handles grid.DataBindingComplete
        InsertUnit()
        InsertPriceFollowCurrency()

        FinishLoad = True
    End Sub

    Private Sub txtTigia_TextChanged(ByVal sender As System.Object, ByVal e As System.EventArgs)
        'uti.FormatCurr(txtTigia)
        'If FinishLoad Then

        '    If txtTigia.Text <> "" Then


        '        For rowIndex = 0 To grid.Rows.Count - 1



        '            'tự động cập nhật lại giá trị của price

        '            Dim clnunit As String = ""
        '            Dim clnquan As String = ""
        '            Dim clnpri As String = ""
        '            Dim clntax As String = ""
        '            Dim clncurr As String = ""
        '            'If isNew Then
        '            '    gridTinhTong = grid
        '            '    clnunit = "UnitPrice"
        '            '    clnquan = "Quantity"
        '            '    clnpri = "Price"
        '            'Else
        '            'gridTinhTong = gridEdit
        '            clnunit = "clnUnitPrice"
        '            clnquan = "clnQuantity"
        '            clnpri = "clnPrice"
        '            clntax = "clnTax"
        '            clncurr = "cbCurrency"
        '            'End If
        '            Try
        '                Dim UnitPrice As Double = Double.Parse(grid.Rows(rowIndex).Cells(clnunit).Value.ToString)
        '                Dim Quantity As Double = Double.Parse(grid.Rows(rowIndex).Cells(clnquan).Value.ToString)
        '                Dim Tax As Double = Double.Parse(grid.Rows(rowIndex).Cells(clntax).Value.ToString)
        '                Dim Currency As String = grid.Rows(rowIndex).Cells(clncurr).Value.ToString

        '                Dim total As Double = UnitPrice * Quantity
        '                If Tax <> 0 Then



        '                    If Currency.Trim() = "VND" Then
        '                    Else
        '                        total = total * txtTigia.Text.ToString().Replace(",", "")

        '                    End If

        '                    total = total + (total * Tax / 100)
        '                Else


        '                    If Currency.Trim() = "VND" Then
        '                    Else
        '                        total = total * txtTigia.Text.ToString().Replace(",", "")

        '                    End If
        '                End If


        '                grid.Rows(rowIndex).Cells(clnpri).Value = total
        '            Catch ex As Exception
        '                grid.Rows(rowIndex).Cells(clnpri).Value = 0
        '            End Try
        '        Next
        '    End If

        'End If
    End Sub

    Private Sub cboCurrency_SelectedIndexChanged(ByVal sender As System.Object, ByVal e As System.EventArgs)
        'Kiểm tra loại tiền

        If FinishLoad = True Then
            InsertPriceFollowCurrency()

        End If

    End Sub
End Class
